package com.weetop.cfw.home_page.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import com.aries.ui.view.radius.RadiusEditText
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.SearchResult
import com.baidu.mapapi.search.geocode.*
import com.blankj.utilcode.util.*
import com.kongzue.dialog.v3.BottomMenu
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.weetop.cfw.R
import com.weetop.cfw.base.presenter.imp.PublishPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.view.PublishView
import com.weetop.cfw.bean.*
import com.weetop.cfw.callback.RxJavaCallBack
import com.weetop.cfw.constants.Constants
import com.weetop.cfw.home_page.adapter.BuildTypeDialog
import com.weetop.cfw.home_page.adapter.IndustryDataDialog
import com.weetop.cfw.home_page.utils.FullyGridLayoutManager
import com.weetop.cfw.home_page.utils.GridImageAdapter
import com.weetop.cfw.utils.*
import kotlinx.android.synthetic.main.activity_publish.*
import org.angmarch.views.NiceSpinner

/**
 * 发布界面
 */
class PublishActivity : CommonBaseActivity(), View.OnClickListener, PublishView {

    companion object {
        private const val EDIT_PUBLISH = "EDIT_PUBLISH"//是编辑还是新建 true:编辑 false:新建
        private const val IS_WORKSHOP_OR_WAREHOUSE =
            "IS_WORKSHOP_OR_WAREHOUSE"//是厂房还是仓库 true:厂房 false:仓库
        private const val INFOID = "INFOID"

        fun startPublishActivity(
            context: Context,
            isEditPublishInfo: Boolean,
            isWorkshopOrWareHouse: Boolean
        ) {
            val intent = Intent(context, PublishActivity::class.java)
            intent.putExtra(EDIT_PUBLISH, isEditPublishInfo)
            intent.putExtra(IS_WORKSHOP_OR_WAREHOUSE, isWorkshopOrWareHouse)
            ActivityUtils.startActivity(intent)
        }

        fun startPublishActivity(
            context: Context,
            isEditPublishInfo: Boolean,
            isWorkshopOrWareHouse: Boolean,
            infoid: Int
        ) {
            val intent = Intent(context, PublishActivity::class.java)
            intent.putExtra(EDIT_PUBLISH, isEditPublishInfo)
            intent.putExtra(IS_WORKSHOP_OR_WAREHOUSE, isWorkshopOrWareHouse)
            intent.putExtra(INFOID, infoid)

            ActivityUtils.startActivity(intent)
        }
    }

    private lateinit var publishPresenterImp: PublishPresenterImp

    private var infoId: Int = 0//新发布出租出售信息的ID 新增发布为0

    private var contentDesc = ""//信息描述

    private var htmlTemplate: String = ""

    private var industryId: String = "-1"//行业ID
    private var industryName: String = ""//行业名称
    private var acrId: String = "-1"//面积分类ID
    private var areaId: String = "-1"//区域ID
    private var cityId: Int = -1//选择的发布站点对应的ID
    private var siteId: Int = -1//站点ID

    private var longitude: String = ""//厂房、仓库所处位置经度
    private var latitude: String = ""//厂房、仓库所处位置维度

    private var priceUnit: String = ""//出租的价格单位

    private var districtAndCountyList: ArrayList<String> = ArrayList()
    private val workshopDetailImageList = ArrayList<String>()

    private var maxSelectedNumber = 1//最多选择的图片数量


    private lateinit var detailAddressAlertDialog: AlertDialog
    private lateinit var buildTypeDialog: BuildTypeDialog
    private lateinit var industryDataDialog: IndustryDataDialog

    private lateinit var detailAddressAlertDialogView: View
    private lateinit var districtAndCountySpinner: NiceSpinner
    private lateinit var editDetailAddress: RadiusEditText

    //上传厂房仓库图片的集合
    private var uploadImagesList = ArrayList<LocalMedia>()

    //上传给后台的HashMap集合
    private val publishParamMap = HashMap<String, String>()

    private var industryStr: String = ""//行业字符串
    private var industryIdStr: String = ""//行业ID字符串
    private var buildTypeStr: String = ""//建筑类型字符串
    private var buildTypeIdStr: String = ""//建筑类型ID字符串

    private var isMotify: Boolean = false
    private var motifyInfoId: Int = 0


    override fun getLayoutId() = R.layout.activity_publish

    override fun initView(savedInstanceState: Bundle?) {
        publishPresenterImp = PublishPresenterImp()
        publishPresenterImp.attachView(this)
        isMotify = intent.getBooleanExtra("isMotify", false)
        motifyInfoId = intent.getIntExtra("motifyInfoId", 0)


        detailAddressAlertDialogView =
            View.inflate(this, R.layout.layout_detail_address_alert_dialog, null)
        districtAndCountySpinner =
            detailAddressAlertDialogView.findViewById<NiceSpinner>(R.id.districtAndCountySpinner)
        editDetailAddress = detailAddressAlertDialogView.findViewById(R.id.editDetailAddress)

        setViewsOnClickListener(
            this,
            imageClearImageItem1,
            imageClearImageItem2,
            imageClearImageItem3,
            imageClearImageItem4,
            imageClearImageItem5,
            imageClearImageItem6,
            imageClearImageItem7,
            imageClearImageItem8,
            imageClearImageItem9,
            imagePublishBack,
            imageChoosePhotoLogo,
            textChoosePhotoLabel,
            textChoosePhotoTip,
            relativeWhetherSublease,
            relativeAloneCourtyard,
            relativeHaveElevator,
            imageUploadImageItem1,
            imageUploadImageItem2,
            imageUploadImageItem3,
            imageUploadImageItem4,
            relativeAddressLocation,
            relativeAddressLocation,
            relativeAreaClassificationContainer,
            relativeIndustryContainer,
            imageUploadImageItem5,
            imageUploadImageItem6,
            imageUploadImageItem7,
            imageUploadImageItem8,
            imageUploadImageItem9,
            relativePublishSite,
            relativeAddressDetail,
            relativeBuildType,
            textMakeSurePublish,
            rlBuildingType
        )

        initDetailAddressDialog()
        if (isMotify) {
            tvDesc.visibility = View.GONE
            editPublishInfoDesc.visibility = View.GONE
            relativePublishAddImageContainer.visibility = View.GONE
            getMotifyDetail()
        }
    }

    private fun getMotifyDetail() {
        RxJavaUtils.useInAppCompatActivityOnDestory(
            RetrofitUtils.getApi().workshopWarehouseDetailData(
                motifyInfoId
            ), this, object :
                RxJavaCallBack<WorkshopWarehouseDetailBean>() {
                override fun onSuccess(t: WorkshopWarehouseDetailBean?) {
                    if (t != null) {
                        //站点
                        textPublishSite.text = t.sitename
                        if (t.siteid != "")
                            siteId = t.siteid.toInt()
                        //详细地址
                        areaId = t.areaid
                        cityId = t.cityid.toInt()

                        editDetailAddress.setText(t.areaname + " " + t.address)
                        textAddressDetail.text = t.address
                        //信息标题
                        editPublishInfoTitle.setText(t.title)
                        //行业
                        industryIdStr = t.vocid.toString()
                        industryStr = t.vocname
                        textIndustry.text = t.vocname
                        //厂房占地面积
                        editAreaCovered.setText(t.coverarea)
                        //出租总面积
                        editRentOutTotalArea.setText(t.totalarea)
                        //起租面积
                        editRentalArea.setText(t.minarea)
                        textBuildingType.text = t.typename
                        buildingTypeIds = t.typeid.split(",") as ArrayList<String>

                        buildingTypeNames = t.typename.split(",") as ArrayList<String>

                        //是否分租
                        if (t.sublet.equals("可以")) {
                            textWhetherSublease.setText("是")
                        } else {
                            textWhetherSublease.setText("否")
                        }
                        editPrice.setText(t.price)
                        editBuildStruct.setText(t.struct)
                        editFloor.setText(t.floor)
                        editFloorHeight.setText(t.fheight)
                        if (t.alone.equals("独院")) {
                            textAloneCourtyard.text = "是"
                        } else {
                            textAloneCourtyard.text = "否"
                        }
                        if (t.lift.equals("电梯")) {
                            textHaveElevator.text = "是"
                        } else {
                            textHaveElevator.text = "否"
                        }
                        editContacts.setText(t.linkman)
                        editPhoneNumber.setText(t.mobile)

                        if (t.phone != null)
                            editFixedTelephone.setText(t.phone)

                    }
                }

                override fun onRequestError(t: WorkshopWarehouseDetailBean?) {
                    super.onRequestError(t)
                }

                override fun onErrorResponse(throwable: Throwable?) {
                    super.onErrorResponse(throwable)
                }
            })
    }

    lateinit var mAdapter: GridImageAdapter
    override fun initData(savedInstanceState: Bundle?) {

        publishParamMap["Token"] = MMKVUtils.getToken()

        val isEdited = intent.getBooleanExtra(EDIT_PUBLISH, false)//是否是编辑发布信息
        if (isEdited) {//是编辑发布信息

        } else {//发布信息
            infoId = 0
            publishParamMap["Infoid"] = "0"
        }

        if (intent!!.getBooleanExtra(IS_WORKSHOP_OR_WAREHOUSE, true)) {
            textRentOutPublishTitle.text = "厂房出租"
        } else {
            textRentOutPublishTitle.text = "仓库出租"
        }

        publishPresenterImp.getSiteInfoByCity(this, Constants.cityName)

        val manager = FullyGridLayoutManager(
            this,
            4, GridLayoutManager.VERTICAL, false
        )
        rcyshow.setLayoutManager(manager)
        mAdapter = GridImageAdapter(this, onAddPicClickListener)
        mAdapter.setSelectMax(9)
        rcyshow.setAdapter(mAdapter)
    }


    private val onAddPicClickListener = GridImageAdapter.onAddPicClickListener {
        PictureSelectorUtils.openAlbumAndCamera(this, 9 - workshopDetailImageList.size)
    }


    /**
     * 移除图片
     * @param position 移除的图片数据在集合中的下标
     * @param clearImage 移除图片的按钮
     * @param imageUploadImageItem
     */
    private fun removePic(position: Int, clearImage: ImageView, imageUploadImageItem: ImageView) {
        uploadImagesList.removeAt(position)

        workshopDetailImageList.removeAt(position)

        clearImage.visibility = View.INVISIBLE

        GlideUtils.loadImage(
            imageUploadImageItem,
            R.mipmap.upload_img_place_holder,
            imageUploadImageItem
        )

        imageUploadImageItem.isEnabled = true

//        maxSelectedNumber += 1

        textUploadImagesNumber.text = "${uploadImagesList.size}/9张"
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.rlBuildingType -> {
                chooseBuildingType()
                rlBuildingType.setEnabled(false)
            }
            R.id.imageClearImageItem1 -> {
                if (uploadImagesList.size >= 1) {
                    removePic(0, imageClearImageItem1, imageUploadImageItem1)
                }
            }
            R.id.imageClearImageItem2 -> {
                if (uploadImagesList.size >= 2) {
                    removePic(1, imageClearImageItem2, imageUploadImageItem2)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem2,
                        imageUploadImageItem2
                    )
                }
            }
            R.id.imageClearImageItem3 -> {
                if (uploadImagesList.size >= 3) {
                    removePic(2, imageClearImageItem3, imageUploadImageItem3)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem3,
                        imageUploadImageItem3
                    )
                }
            }
            R.id.imageClearImageItem4 -> {
                if (uploadImagesList.size >= 4) {
                    removePic(3, imageClearImageItem4, imageUploadImageItem4)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem4,
                        imageUploadImageItem4
                    )
                }
            }
            R.id.imageClearImageItem5 -> {
                if (uploadImagesList.size >= 5) {
                    removePic(4, imageClearImageItem5, imageUploadImageItem5)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem5,
                        imageUploadImageItem5
                    )
                }
            }
            R.id.imageClearImageItem6 -> {
                if (uploadImagesList.size >= 6) {
                    removePic(5, imageClearImageItem6, imageUploadImageItem6)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem6,
                        imageUploadImageItem6
                    )
                }
            }
            R.id.imageClearImageItem7 -> {
                if (uploadImagesList.size >= 7) {
                    removePic(6, imageClearImageItem7, imageUploadImageItem7)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem7,
                        imageUploadImageItem7
                    )
                }
            }
            R.id.imageClearImageItem8 -> {
                if (uploadImagesList.size >= 8) {
                    removePic(7, imageClearImageItem8, imageUploadImageItem8)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem8,
                        imageUploadImageItem8
                    )
                }
            }
            R.id.imageClearImageItem9 -> {
                if (uploadImagesList.size >= 9) {
                    removePic(8, imageClearImageItem9, imageUploadImageItem9)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem9,
                        imageUploadImageItem9
                    )
                }
            }
            R.id.imagePublishBack -> ActivityUtils.finishActivity(this)
            R.id.imageChoosePhotoLogo, R.id.textChoosePhotoLabel, R.id.textChoosePhotoTip -> PictureSelectorUtils.openAlbumAndCamera(
                this,
                (9 - workshopDetailImageList.size)
            )
            R.id.relativeWhetherSublease -> showWhetherSubleaseBottomMenu()
            R.id.relativeAloneCourtyard -> showAloneCourtyardBottomMenu()
            R.id.relativeHaveElevator -> showHaveElevatorBottomMenu()
            R.id.imageUploadImageItem1, R.id.imageUploadImageItem2, R.id.imageUploadImageItem3, R.id.imageUploadImageItem4,
            R.id.imageUploadImageItem5, R.id.imageUploadImageItem6, R.id.imageUploadImageItem7, R.id.imageUploadImageItem8, R.id.imageUploadImageItem9 -> PictureSelectorUtils.openAlbumAndCamera(
                this,
                1
            )
            R.id.relativeAreaClassificationContainer -> publishPresenterImp.areaClassificationList(
                this
            )
            R.id.relativeIndustryContainer -> {
                publishPresenterImp.getIndustryList(this)
                relativeIndustryContainer.setEnabled(false)
            }
            R.id.relativePublishSite -> publishPresenterImp.getAllSitesData(this)
            R.id.relativeAddressDetail -> publishPresenterImp.getDistrictAndCountyData(this, cityId)
            R.id.relativeAddressLocation -> {
                val mapIntent = Intent(this@PublishActivity, BaiDuMapActivity::class.java)
                startActivityForResult(mapIntent, 0)
            }
            R.id.relativeBuildType -> publishPresenterImp.getBuildType(this)
            R.id.textMakeSurePublish -> {


                when {
                    textPublishSite.text.toString() == "请选择" -> {
                        showNativeShortToast("请选择发布站点")
                    }
                    textAddressDetail.text.toString() == "请选择" -> {
                        showNativeShortToast("请选择详细地址")
                    }
                    editPublishInfoTitle.text.toString().trim() == "" -> {
                        showNativeShortToast("请填写信息标题")
                    }
//                    textBuildType.text.toString() == "请选择" -> {
//                        showNativeShortToast("请选择建筑类型")
//                    }
                    editRentOutTotalArea.text.toString().trim() == "" -> {
                        showNativeShortToast("请填写出租总面积")
                    }
                    editContacts.text.toString().trim() == "" -> {
                        showNativeShortToast("请填写联系人姓名")
                    }
                    textWhetherSublease.text.toString().trim() == "请选择" -> {
                        showNativeShortToast("请填写是否分租")
                    }
                    editPrice.text.toString().trim() == "" -> {
                        showNativeShortToast("请填写价格")
                    }
                    textAloneCourtyard.text.toString().trim() == "" -> {
                        showNativeShortToast("请填写是否独院")
                    }
                    textHaveElevator.text.toString().trim() == "请选择" -> {
                        showNativeShortToast("请填写是否有无电梯")
                    }


                    !RegexUtils.isMobileSimple(editPhoneNumber.text.toString().trim()) -> {
                        showNativeShortToast("请填写正确手机号码")
                    }
                    buildingTypeIds.size == 0 -> {
                        showNativeShortToast("请选择建筑类型")
                    }
                    else -> {
                        publishParamMap["Vocid"] = industryIdStr.dropLast(1)
                        publishParamMap["vocname"] = industryStr.dropLast(1)
//                        publishParamMap["Acrid"] = acrId
                        publishParamMap["Areaid"] = areaId
                        publishParamMap["siteid"] = siteId.toString()

                        publishParamMap["title"] = editPublishInfoTitle.text.toString().trim()
                        publishParamMap["Intid"] = "1"
                        var ids = ""
                        var names = ""
                        for (buildingTypeId in buildingTypeIds) {
                            ids += "$buildingTypeId,"
                        }

                        for (buildingTypeName in buildingTypeNames) {
                            names += "$buildingTypeName,"
                        }

                        publishParamMap["Typeid"] = ids.substring(0, ids.length - 1)
                        publishParamMap["Typename"] = names.substring(0, names.length - 1)

                        publishParamMap["Address"] = editDetailAddress.text.toString().trim()
                        publishParamMap["Totalarea"] =
                            editRentOutTotalArea.text.toString().trim()
                        publishParamMap["Coverarea"] = editAreaCovered.text.toString().trim()
                        publishParamMap["Minarea"] = editRentalArea.text.toString().trim()

                        if (textAloneCourtyard.text.toString() == "请选择") {
                            publishParamMap["Isalone"] = ""
                        } else {
                            publishParamMap["Isalone"] =
                                if (textAloneCourtyard.text.toString() == "是") "1" else "0"
                        }

                        if (textWhetherSublease.text.toString() == "请选择") {
                            publishParamMap["issublet"] = ""
                        } else {
                            publishParamMap["issublet"] =
                                if (textWhetherSublease.text.toString() == "是") "1" else "0"
                        }

                        publishParamMap["Useyearmin"] = ""
                        publishParamMap["Useyearmax"] = ""
                        publishParamMap["Price"] = editPrice.text.toString().trim()
                        publishParamMap["Punit"] = priceUnit
                        publishParamMap["Maplat"] = latitude
                        publishParamMap["maplng"] = longitude
                        publishParamMap["Sstruct"] = editBuildStruct.text.toString().trim()
                        publishParamMap["Floor"] = editFloor.text.toString().trim()
                        publishParamMap["Fheight"] = editFloorHeight.text.toString().trim()
                        publishParamMap["Housecer"] = ""
                        publishParamMap["landcer"] = ""

                        if (textHaveElevator.text.toString() == "请选择") {
                            publishParamMap["Haslift"] = ""
                        } else {
                            publishParamMap["Haslift"] =
                                if (textHaveElevator.text.toString() == "有") "1" else "0"
                        }

                        publishParamMap["Linkman"] = editContacts.text.toString().trim()
                        publishParamMap["Phone"] = editFixedTelephone.text.toString().trim()
                        publishParamMap["Mobile"] = editPhoneNumber.text.toString().trim()
//                            generateHtmlTemplate(editPublishInfoDesc.text.toString().trim())


                        if (isMotify) {
                            publishParamMap["Infoid"] = motifyInfoId.toString()
                            publishPresenterImp.publishLeaseSaleInformation(
                                this@PublishActivity,
                                publishParamMap
                            )
                        } else {
                            publishParamMap["Infoid"] = "0"
                            if (workshopDetailImageList.size >= 1) {
                                publishParamMap["Imgfile"] = workshopDetailImageList[0]
                            } else {
                                publishParamMap["Imgfile"] = ""
                            }

                            var imglist: String = ""
                            for (i in workshopDetailImageList.indices) {
                                if (i != 0) {
                                    imglist += workshopDetailImageList[i] + ","
                                }
                            }
//                            for (s in workshopDetailImageList) {
//                                imglist += s + ","
//                            }
                            if (imglist.length > 1) {
                                publishParamMap["Imglist"] =
                                    imglist.substring(0, imglist.length - 1)
                            } else {
                                publishParamMap["Imglist"] = ""
                            }
                            publishParamMap["Content"] = editPublishInfoDesc.text.toString().trim()

                            publishPresenterImp.publishLeaseSaleInformation(
                                this@PublishActivity,
                                publishParamMap
                            )
                        }

                    }


                }
            }
        }
    }

    private var buildingTypeIds = ArrayList<String>()
    private var buildingTypeNames = ArrayList<String>()

    private fun chooseBuildingType() {
        RxJavaUtils.useInAppCompatActivityOnDestory(
            RetrofitUtils.getApi().generalCodeTable(1200),
            this@PublishActivity,
            object : RxJavaCallBack<GeneralCodeTableBean>() {
                override fun onSuccess(t: GeneralCodeTableBean?) {
                    if (t != null) {
//                        val industry = ArrayList<String>()
//                        val ids = ArrayList<Int>()
                        val industryInfoList = t.data
//                        for (itemIndustry in industryInfoList) {
//                            industry.add(itemIndustry.codename)
//                            ids.add(itemIndustry.codeid)
//                        }
//                        LogUtils.eTag("industry", industry)


//                    BottomMenu.show(this@PublishActivity, industry) { text, index ->
//                        if (textIndustry.text.toString().contains(industry[index])){
//                            buildingTypeIds.add()
//                        }
//                        textIndustry.setTextColor(ColorUtils.getColor(R.color.colorAccent))
//                        //返回参数 text 即菜单名称，index 即菜单索引
//                        textIndustry.text =
//                            Editable.Factory.getInstance().newEditable(industryStr.dropLast(1))
//                    }


//                        var baseAdapter =
//                            ChooseAdapter(industryInfoList as java.util.ArrayList<GeneralCodeTableBean.DataBean>)
//
//                        BottomMenu.show(this@PublishActivity, baseAdapter) { text, index ->
//
//
//                            if (textBuildingType.text.toString()
//                                    .contains(industryInfoList[index].codename)
//                            ) {
//                                buildingTypeIds.remove(industryInfoList[index].codeid.toString())
//                                buildingTypeNames.remove(industryInfoList[index].codename)
//                            } else {
//                                buildingTypeIds.add(industryInfoList[index].codeid.toString())
//                                buildingTypeNames.add(industryInfoList[index].codename)
//                            }
//
//                            var textshow = ""
//                            for (buildingTypeName in buildingTypeNames) {
//                                textshow += "${buildingTypeName},"
//                            }
//                            textBuildingType.text = textshow
//                        }


                        val buildKindArray = ArrayList<String>()
                        val list1 = ArrayList<Boolean>()

                        industryInfoList.forEach { dataBean ->
                            buildKindArray.add(dataBean.codename)
                            list1.add(false)
                        }
                        rlBuildingType.setEnabled(true)
                        buildTypeDialog =
                            BuildTypeDialog(
                                this@PublishActivity,
                                t.data,
                                buildKindArray,
                                list1,
                                "选择建筑类型"
                            )
                        buildTypeDialog.show()

                    }
                }

                override fun onRequestError(t: GeneralCodeTableBean?) {
                    super.onRequestError(t)
                    rlBuildingType.setEnabled(true)
                }

            })
    }


    private inner class ChooseAdapter(infos: java.util.ArrayList<GeneralCodeTableBean.DataBean>) :
        BaseAdapter() {
        private var infos = java.util.ArrayList<GeneralCodeTableBean.DataBean>()

        init {
            this.infos = infos
        }

        override fun getCount(): Int {
            return infos.size
        }

        override fun getItem(position: Int): Any? {
            return infos[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
            var view = View.inflate(this@PublishActivity, R.layout.item_bottom_menu_ios, null)
            var text = view.findViewById<TextView>(R.id.text)
            text.text = infos.get(position).codename
            if (textBuildingType.text.contains(infos.get(position).codename)) {
                text.setTextColor(Color.parseColor("#ff0000"))
            } else {
                text.setTextColor(Color.parseColor("#0000ff"))
            }

            return view
        }
    }


    /**
     * 生成HTML模板
     */
    private fun generateHtmlTemplate(contentDesc: String): String {
        var html = ""
        return if (workshopDetailImageList.size >= 2) {
            var htmlDoc = ""
            for (item in workshopDetailImageList) {
                if (workshopDetailImageList.indexOf(item) != 0) {
                    htmlDoc =
                        "<img src=\"${item}\" style=\"vertical-align: middle; max-width: 100%;\">"
                    htmlDoc += htmlDoc
                }
            }
            html =
                "<p style=\"margin-top: 0px; margin-bottom: 0px; padding: 0px 0px 24px; text-align: center; color: rgb(27, 27, 27); font-family: &quot;Microsoft YaHei&quot;, &quot;Hiragino Sans GB&quot;, &quot;WenQuanYi Micro Hei&quot;, 微软雅黑, 宋体, sans-serif; font-size: 18px; white-space: normal; background-color: rgb(255, 255, 255);\"><span style=\"color: rgb(27, 27, 27); font-family: &quot;Microsoft YaHei&quot;, &quot;Hiragino Sans GB&quot;, &quot;WenQuanYi Micro Hei&quot;, 微软雅黑, 宋体, sans-serif; font-size: 18px; text-indent: 36px; white-space: normal; background-color: rgb(255, 255, 255);\">${contentDesc}</span></p><p style=\"margin-top: 0px; margin-bottom: 0px; padding: 0px 0px 24px; text-align: center; color: rgb(27, 27, 27); font-family: &quot;Microsoft YaHei&quot;, &quot;Hiragino Sans GB&quot;, &quot;WenQuanYi Micro Hei&quot;, 微软雅黑, 宋体, sans-serif; font-size: 18px; white-space: normal; background-color: rgb(255, 255, 255);\">${htmlDoc}</p>"
            LogUtils.dTag("generateHtmlTemplate", html)
            return html
        } else {
            ""
        }
    }

    private var currentList = ArrayList<LocalMedia>()
    private var uploadPosition = 0
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    // 图片、视频、音频选择结果回调
                    val selectList = PictureSelector.obtainMultipleResult(data)
                    //将选择的图片数据集合添加到集合中
                    uploadPosition = 0
                    currentList.clear()
                    currentList.addAll(selectList)
                    if (currentList[0].isCompressed) {
                        publishPresenterImp.uploadWorkshopDetailImage(
                            this@PublishActivity,
                            currentList[0].compressPath
                        )
                    } else {
                        publishPresenterImp.uploadWorkshopDetailImage(
                            this@PublishActivity,
                            currentList[0].path
                        )
                    }
//
//                    for (item in selectList) {

//                    }

                }
            }
        }
    }

    /**
     * 根据经纬度获取详细地址
     * @param latLng 包含经纬度信息的对象
     */
    private fun getDetailAddressByLatLng(latLng: LatLng) {
        val geoCoder = GeoCoder.newInstance()
        geoCoder.setOnGetGeoCodeResultListener(object : OnGetGeoCoderResultListener {

            override fun onGetGeoCodeResult(p0: GeoCodeResult?) {

            }


            override fun onGetReverseGeoCodeResult(reverseGeoCodeResult: ReverseGeoCodeResult) {
                if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    // 没有检测到结果
                    return
                }
                val addressDetail = reverseGeoCodeResult.addressDetail
                //需要的地址信息就在AddressComponent 里
                textAddressLocation.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textAddressLocation.text =
                    "${addressDetail.province}${addressDetail.city}${addressDetail.district}${addressDetail.town}${addressDetail.street}${addressDetail.streetNumber}"
            }
        })
        geoCoder.reverseGeoCode(ReverseGeoCodeOption().location(latLng))
    }

    override fun onDestroy() {
        super.onDestroy()
        publishPresenterImp.detachView()
    }

    /**
     * 展示厂房是否可以分租的底部对话框
     */
    private fun showWhetherSubleaseBottomMenu() {
        BottomMenu.show(this@PublishActivity, arrayOf("可分租", "不可分租")) { text, index ->
            textWhetherSublease.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textWhetherSublease.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    /**
     * 展示厂房是否是独院的底部对话框
     */
    private fun showAloneCourtyardBottomMenu() {
        BottomMenu.show(this@PublishActivity, arrayOf("是", "否")) { text, index ->
            textAloneCourtyard.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textAloneCourtyard.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    /**
     * 展示厂房是否有电梯的底部对话框
     */
    private fun showHaveElevatorBottomMenu() {
        BottomMenu.show(this@PublishActivity, arrayOf("有", "无")) { text, index ->
            textHaveElevator.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textHaveElevator.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    /**
     * 展示发布站点的底部对话框
     */
    private fun showPublishSiteBottomMenu(allSitesDataBean: List<AllSitesBean.DataBean>) {
        LogUtils.d("allSitesDataBean", allSitesDataBean)
        val sitesArray = ArrayList<String>()
        for (i in allSitesDataBean.indices) {
            sitesArray.add(allSitesDataBean[i].sitename)
            //LogUtils.e("sitename", allSitesDataBean[i].sitename)
        }

        BottomMenu.show(this@PublishActivity, sitesArray) { text, index ->
            siteId = allSitesDataBean[index].siteid
            cityId = allSitesDataBean[index].cityid

            publishPresenterImp.getPriceUnitBySiteId(this@PublishActivity, siteId)

            textPublishSite.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textPublishSite.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

//    /**
//     * 展示建筑类型选择的底部对话框
//     */
//    private fun showBuildTypeBottomMenu(kindDataBeanList: List<KindBean.DataBean>) {
//        val buildKindArray = ArrayList<String>()
//
//        kindDataBeanList.forEach { dataBean ->
//            buildKindArray.add(dataBean.codename)
//        }
//
//        LogUtils.d("buildKindArray", buildKindArray)
//        BottomMenu.show(this@PublishActivity, buildKindArray) { text, index ->
//
//            buildTypeIdStr += "${kindDataBeanList[index].codeid},"
//            buildTypeStr += "${kindDataBeanList[index].codename},"
//
//
//            textBuildType.setTextColor(ColorUtils.getColor(R.color.colorAccent))
//            //返回参数 text 即菜单名称，index 即菜单索引
//            textBuildType.text =
//                Editable.Factory.getInstance().newEditable(buildTypeStr.dropLast(1))
//
//k
//        }
//    }

    /**
     * 展示建筑类型选择的底部对话框 修改
     */
    private fun showBuildTypeBottomMenu(kindDataBeanList: List<KindBean.DataBean>) {
        val buildKindArray = ArrayList<String>()
        val list1 = ArrayList<Boolean>()

        kindDataBeanList.forEach { dataBean ->
            buildKindArray.add(dataBean.codename)
            list1.add(false)
        }
//        buildTypeDialog =
//            BuildTypeDialog(this@PublishActivity, kindDataBeanList, buildKindArray, list1, "选择建筑类型")
//        buildTypeDialog.show()
    }

    public fun getSelectList(
        mList: java.util.ArrayList<String>,
        idList: java.util.ArrayList<String>
    ) {

        buildTypeIdStr = ""
        buildTypeStr = ""
        buildingTypeIds.clear()
        buildingTypeNames.clear()
        for (i in mList.indices) {
            buildingTypeIds.add(idList[i])
            buildingTypeNames.add(mList[i])
            buildTypeStr = buildTypeStr + mList[i] + ","
            buildTypeIdStr = buildTypeIdStr + idList[i] + ","
        }
        textBuildingType.setTextColor(ColorUtils.getColor(R.color.colorAccent))
        textBuildingType.text = buildTypeStr

    }


    /**
     * 所有分站数据获取成功
     */
    override fun getAllSitesDataSuccess(allSitesBean: AllSitesBean?) {
        if (allSitesBean != null) {
            LogUtils.d("allSitesBean", allSitesBean)
            showPublishSiteBottomMenu(allSitesBean.data)
        }
    }

    /**
     * 建筑类型数据获取成功
     */
    override fun getBuildKindDataSuccess(kindBean: KindBean?) {
        if (kindBean != null) {
            showBuildTypeBottomMenu(kindBean.data)
        }
    }

    /**
     * 出租出售信息发布成功
     */
    override fun leaseSaleInformationPublishSuccess(errorBean: PublishBean?) {
        if (errorBean != null) {
            if (isMotify) {
                ToastUtils.showShort("修改成功")
                finish()
            } else {
                ToastUtils.showShort("发布成功")
                showNativeShortToast(errorBean.message)
                var intent = Intent(this, AdPayToTopActivity::class.java)
                intent.putExtra("infoId", errorBean.infoid)
                startActivity(intent)
                finish()
            }
        }
    }

    /**
     * 行业数据列表请求成功
     */
    override fun industryDataGetSuccess(generalCodeTableBean: GeneralCodeTableBean?) {
//        if (generalCodeTableBean != null) {
//            val industry = ArrayList<String>()
//            val industryInfoList = generalCodeTableBean.data
//            for (itemIndustry in industryInfoList) {
//                industry.add(itemIndustry.codename)
//            }
//            LogUtils.eTag("industry", industry)
//            BottomMenu.show(this@PublishActivity, industry) { text, index ->
//
//                industryId = generalCodeTableBean.data[index].codeid.toString()
//                industryName = generalCodeTableBean.data[index].codename
//
//                if (StringUtils.isEmpty(industryStr) || !industryStr.contains(industryName)) {
//                    industryIdStr += "${industryId},"
//                    industryStr += "${industryName},"
//                }
//
//                textIndustry.setTextColor(ColorUtils.getColor(R.color.colorAccent))
//                //返回参数 text 即菜单名称，index 即菜单索引
//                textIndustry.text =
//                    Editable.Factory.getInstance().newEditable(industryStr.dropLast(1))
//            }
//        }


        relativeIndustryContainer.setEnabled(true)
        if (generalCodeTableBean != null) {
            val buildKindArray = ArrayList<String>()
            val list1 = ArrayList<Boolean>()

            val industryInfoList = generalCodeTableBean.data
            for (itemIndustry in industryInfoList) {
                buildKindArray.add(itemIndustry.codename)
                list1.add(false)
            }
            industryDataDialog =
                IndustryDataDialog(
                    this@PublishActivity,
                    generalCodeTableBean.data,
                    buildKindArray,
                    list1,
                    "选择行业"
                )
            industryDataDialog.show()
        }
    }


    public fun getSelectList1(
        mList: java.util.ArrayList<String>,
        idList: java.util.ArrayList<String>
    ) {

        industryIdStr = ""
        industryStr = ""
        for (i in mList.indices) {
            industryStr = industryStr + mList[i] + ","
            industryIdStr = industryIdStr + idList[i] + ","
        }
        textIndustry.setTextColor(ColorUtils.getColor(R.color.colorAccent))
        textIndustry.text = industryStr

    }


    /**
     * 面积归类数据请求成功
     */
    override fun areaClassificationDataGetSuccess(generalCodeTableBean: GeneralCodeTableBean?) {
        if (generalCodeTableBean != null) {
            val areaClassification = ArrayList<String>()
            val areaClassificationInfoList = generalCodeTableBean.data
            for (itemIndustry in areaClassificationInfoList) {
                areaClassification.add(itemIndustry.codename)
            }
            LogUtils.eTag("areaClassification", areaClassification)
            BottomMenu.show(this@PublishActivity, areaClassification) { text, index ->

                acrId = generalCodeTableBean.data[index].codeid.toString()

                textAreaClassification.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                //返回参数 text 即菜单名称，index 即菜单索引
                textAreaClassification.text = Editable.Factory.getInstance().newEditable(text)
            }
        }
    }

    /**
     * 发布站点下面的区县信息获取成功
     */
    override fun getDistrictAndCountyDataSuccess(siteBean: SiteBean?) {
        if (siteBean != null) {
            districtAndCountyList = ArrayList<String>()
            for (item in siteBean.data) {
                districtAndCountyList.add(item.areaname)
            }
            districtAndCountySpinner.attachDataSource(districtAndCountyList)
            areaId = siteBean.data[0].areaid.toString()
            districtAndCountySpinner.setOnSpinnerItemSelectedListener { parent, view, position, id ->
                areaId = siteBean.data[position].areaid.toString()
            }
            detailAddressAlertDialog.show()
        }
    }

    /**
     * 当前城市对应的站点信息获取成功
     */
    override fun siteInfoGetSuccess(cityIdBean: CityIdBean?) {
        if (cityIdBean != null) {
            cityId = cityIdBean.cityid
            siteId = cityIdBean.siteid

            publishPresenterImp.getPriceUnitBySiteId(this, siteId)

            textPublishSite.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            textPublishSite.text = cityIdBean.sitename
        }
    }

    override fun getPriceUnitSuccess(priceUnit: String?) {
        if (priceUnit != null) {
            textPriceUnit.text = priceUnit
            this.priceUnit = priceUnit
        }
    }

    /**
     * 上传图片成功
     * @param imageUrl 图片链接
     */
    override fun uploadImageSuccess(imageUrl: String) {

        LogUtils.eTag("uploadImageSuccess", imageUrl)
//        workshopDetailImageList.add("${UrlConstants.baseUrl}${imageUrl}")
        workshopDetailImageList.add(imageUrl)
        uploadImagesList.add(currentList[uploadPosition])
        mAdapter.setList(uploadImagesList, workshopDetailImageList)

        if (uploadImagesList.size > 0) {
            rlCover.visibility = View.GONE
            rcyshow.visibility = View.VISIBLE
        } else {
            rlCover.visibility = View.VISIBLE
            rcyshow.visibility = View.GONE
        }
        mAdapter.notifyDataSetChanged()
        uploadPosition += 1

        if (uploadPosition + 1 <= currentList.size) {
            if (currentList[uploadPosition].isCompressed) {
                publishPresenterImp.uploadWorkshopDetailImage(
                    this@PublishActivity,
                    currentList[uploadPosition].compressPath
                )
            } else {
                publishPresenterImp.uploadWorkshopDetailImage(
                    this@PublishActivity,
                    currentList[uploadPosition].path
                )
            }
        } else {
            uploadPosition = 0
        }
    }

    override fun uploadImageError() {
        uploadPosition += 1
        if (uploadPosition + 1 <= currentList.size) {
            if (currentList[uploadPosition].isCompressed) {
                publishPresenterImp.uploadWorkshopDetailImage(
                    this@PublishActivity,
                    currentList[uploadPosition].compressPath
                )
            } else {
                publishPresenterImp.uploadWorkshopDetailImage(
                    this@PublishActivity,
                    currentList[uploadPosition].path
                )
            }
        } else {
            uploadPosition = 0
        }
    }

    /**
     * 初始化选择详细地址的对话框
     */
    private fun initDetailAddressDialog() {
        detailAddressAlertDialog = AlertDialog.Builder(this)
            .setCancelable(true)
            .setView(detailAddressAlertDialogView)
            .setPositiveButton(
                "确定"
            ) { dialog, which ->
                textAddressDetail.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textAddressDetail.text =
                    "${districtAndCountyList[districtAndCountySpinner.selectedIndex]} ${editDetailAddress.text.toString()
                        .trim()}"
            }
            .setNegativeButton("取消", null)
            .create()
    }

}
